import { defineConfig, loadEnv } from "vite";
import path from "path";

import vue from "@vitejs/plugin-vue";

import autoImport from "unplugin-auto-import/vite";
import PreprocessorDirectives from "unplugin-preprocessor-directives/vite";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

// svg icon
export function createSvgIcon(isBuild) {
  return createSvgIconsPlugin({
    iconDirs: [path.resolve(process.cwd(), "src/assets/icons/svg")],
    symbolId: "icon-[dir]-[name]",
    svgoOptions: isBuild,
  });
}

// auto import
// 自动导入vue、vue-router、pinia等常用api
export function createAutoImport() {
  return autoImport({
    imports: ["vue", "vue-router", "pinia"],
    dts: false,
  });
}
// todo: 需要配置环境变量
// https://vite.dev/config/
export default defineConfig(({ mode, command }) => {
  return {
    plugins: [vue(), createAutoImport(), PreprocessorDirectives({})],
    base: mode === "production" ? "/" : "/",
    resolve: {
      alias: {
        "~": path.resolve(__dirname, "./"),
        "@": path.resolve(__dirname, "./src"),
      },
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
    },

    server: {
      port: 1430,
      strictPort: true,
      open: true,
      proxy: {
        "/api": {
          target: "http://127.0.0.1:18080",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, "/api"),
        },
      },
    },
    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: "internal:charset-removal",
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === "charset") {
                  atRule.remove();
                }
              },
            },
          },
        ],
      },
    },
  };
});
